const { exec } = require("../db/mysql.js");
const getList = (author, keyword) => {
  let sql = "select * from blogs where 1=1 ";
  if (author) {
    sql += `and author='${author}' `;
  }
  if (keyword) {
    sql += `and title like '%${keyword}%' `;
  }
  sql += 'order by createtime desc;';

  return exec(sql);

}

const getDetail = (id) => {
  var sql = `select * from blogs where id=${id} `;

  return exec(sql);
  // return {
  //   id: 1,
  //   title: '标题a',
  //   content: '内容a',
  //   createTime: '1602565292751',
  //   author: 'zhangsan'
  // }
}

const newBlog = (blogData = {}) => {
  // blogData是博客对象，包含title content,author,createTime属性
  console.log("新建博客内容:", blogData);
  let { title,content,author,createTime } = blogData;
  var sql = `insert into blogs(title, content, author, createTime) values ("${title}","${content}","${author}",${createTime});`;
  return exec(sql);
  // return {
  //   id: 3
  // }
}

const updateBlog = (id, blogData = {}) => {
  // blogData是博客对象，包含title content属性
  console.log("更新博客内容:", id, blogData);
  let { title,content } = blogData;
  var sql = `update blogs set title="${title}", content="${content}" where id=${id}`;
  return exec(sql);
  //return Math.random() > 0.5 ? true : false;
}

const delBlog = (id, author) => {
  // id 要删除的博客
  console.log("要删除的博客id:", id);
  let sql = `delete from blogs where id=${id} and author=${author}`
  return exec(sql);
}

module.exports = {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  delBlog
}